use super::APP_STATE;
use crate::network::WriteMessage;
use crate::{file_manager, interface::build_reply, AppState};
use bincode::{deserialize, serialize};
use core::sync;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::io::AsyncWriteExt;
use tokio::sync::Mutex;

#[derive(Serialize, Deserialize, Debug)]
pub enum NetworkDataTypeNetData {
    // 客户端发送的消息
    FILEMETA,  // 文件的元数据
    FILEDATA,  // 文件的具体的内容
    FILEEND,   // 文件传输完毕
    FILEREPLY, // 请求的回应
}

#[derive(Serialize, Deserialize, Debug)]
pub struct NetworkDataNetData {
    pub data_type: NetworkDataTypeNetData,
    pub data: Vec<u8>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct FileMetaNetData {
    pub file_id: u32, // 文件id，用于唯一的标识
    pub file_name: String,
    pub file_size: u64,  // 单位：字节
    pub request_id: u64, // 询问的请求
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FileDataNetData {
    pub file_id: u32,
    pub file_offset: u64,
    pub file_data: Vec<u8>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct FileEndNetData {
    pub file_id: u32,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct FileReplyNetData {
    pub request_id: u64,
    pub reply: u64,
}

pub async fn process(
    app_state: Arc<AppState>,
    network_data: Vec<u8>,
    writer: Option<Arc<Mutex<tokio::net::tcp::OwnedWriteHalf>>>,
) {
    if network_data.is_empty() {
        println!("空字符，不用处理");
        return;
    }
    let data: NetworkDataNetData = deserialize(&network_data[..]).expect("网络数据反序列化失败");
    match data.data_type {
        NetworkDataTypeNetData::FILEMETA => {
            let file_meta: FileMetaNetData =
                deserialize(&data.data[..]).expect("文件元数据反序列化失败");
            let sync_point = file_meta.request_id;
            let mut file_manager = app_state.file_manager.lock().await;
            file_manager
                .add_file(file_meta.file_id, file_meta.file_name, file_meta.file_size)
                .await
                .expect("添加文件失败");
            // 处理结束以后，则发送处理结束
            let reply: Vec<u8> = build_reply(sync_point, 0);
            if let Some(writer) = writer {
                let mut guard: tokio::sync::MutexGuard<'_, tokio::net::tcp::OwnedWriteHalf> =
                    writer.lock().await;
                (*guard)
                    .send_message(&reply)
                    .await
                    .expect("Failed to send message");
            }
        }
        NetworkDataTypeNetData::FILEDATA => {
            let file_data: FileDataNetData =
                deserialize(&data.data[..]).expect("文件数据反序列化失败");
            let file_manager = app_state.file_manager.lock().await;
            let _ = file_manager.add_file_block(file_data).await;
        }
        NetworkDataTypeNetData::FILEEND => {
            let file_end: FileEndNetData =
                deserialize(&data.data[..]).expect("文件结束反序列化失败");
            let mut file_manager = app_state.file_manager.lock().await;
            file_manager.finish_file(file_end.file_id).await;
        }
        NetworkDataTypeNetData::FILEREPLY => {
            // 处理文件回复
            let file_reply: FileReplyNetData =
                deserialize(&data.data[..]).expect("文件回复反序列化失败");
            app_state
                .sync_manager
                .release_sync_point(file_reply.request_id, file_reply.reply)
                .await;
        }
        _ => {}
    }
}
